package com.gph.saviorframework.util;

import com.gph.saviorframework.annotation.KeyGenerator;
import com.gph.saviorframework.common.model.Sequences;
import com.gph.saviorframework.generator.service.SequencesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 主键生成器，通过SF_SEQUENCES中的k-v值设置
 */
@Component
public class KeyGeneratorUtils {

    @Autowired
    private SequencesService sequencesService;

    /**
     * 根据传输过来的class获取主键的值
     * @param clazz
     */
    public int getKeyValue(Class clazz){
        try {
            Field[] fields = clazz.getDeclaredFields();
            for(Field field : fields){
                KeyGenerator keyGenerator = field.getAnnotation(KeyGenerator.class);
                if(keyGenerator != null){
                    //说明有注解
                    //第一步:先判断数据库是否有数据
                    Sequences sequences = get(keyGenerator.segmentValue());
                    if(sequences != null){
                        //如果有数据存在就返回nextVal，并将nextVal加1更新到数据库中
                        sequences.setNextVal(sequences.getNextVal()+1);
                        sequencesService.update(sequences);

                        return sequences.getNextVal();
                    }
                    else{
                        //如果没有数据不存在，就返回初始值，并将初始值加1存储到数据库中
                        sequences = new Sequences();
                        sequences.setNextVal(keyGenerator.initialValue()+1);
                        sequences.setSequenceName(keyGenerator.segmentValue());
                        sequencesService.save(sequences);

                        return keyGenerator.initialValue();
                    }
                }
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

        return 0;
    }

    /**
     * SEQUENCE_NAME是否存在
     * @return
     */
    private boolean isExistSegment(String segmentName){
        Sequences sequences = sequencesService.get(segmentName);
        if(sequences!=null){
            return true;
        }
        return false;
    }

    private Sequences get(String segmentName){
        Sequences sequences = sequencesService.get(segmentName);
        if(sequences!=null){
            return sequences;
        }
        return null;
    }
}
